package com.lej.location

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.content.ContextCompat

/**
 * 定位辅助类 判断是否有定位权限
 * 使用注意 必须要调用onRequestPermissionsResult用于获取权限回调
 * 必须要在页面关闭时调用destroyLocation方法
 */
class LocationHelper(
    context: Context,
    private val mLocationListener: LocationListener,//定位回调
    private val mLocationInterface: LocationInterface = AmapLocation()//定位实现接口
) {

    init {
        this.mLocationInterface.init(context, mLocationListener)
    }

    /**
     * 启动定位
     */
    fun startLocation(context: Context) {
        if (!hasPermission(context)) {
            mLocationListener.noPermissions()
            return
        }
        mLocationInterface.startLocation()
    }

    /**
     * 检查是否有权限
     */
    private fun hasPermission(context: Context): Boolean {
        return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            true
        } else checkPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
                && checkPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
    }

    /**
     * 检查是否有权限
     */
    private fun checkPermission(context: Context, permission: String): Boolean {
        return ContextCompat.checkSelfPermission(context, permission) ==
                PackageManager.PERMISSION_GRANTED
    }

    /**
     * 关闭定位
     */
    fun stopLocation() {
        mLocationInterface.stopLocation()
    }

    /**
     * 释放资源
     */
    fun destroyLocation() {
        mLocationInterface.destroyLocation()
    }
}